package cn.stylefeng.guns.modular.tool.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.tool.entity.ToolStorageStock;
import cn.stylefeng.guns.modular.tool.mapper.ToolStorageStockMapper;
import cn.stylefeng.guns.modular.tool.model.params.ToolStorageStockParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolStorageStockResult;
import  cn.stylefeng.guns.modular.tool.service.ToolStorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * <p>
 * 云仓库存表 服务实现类
 * </p>
 * @author zhucx
 * @since 2023-04-01
 */
@Service
public class ToolStorageStockServiceImpl extends ServiceImpl<ToolStorageStockMapper, ToolStorageStock> implements ToolStorageStockService {

    @Override
    public void add(ToolStorageStockParam param){
        ToolStorageStock entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ToolStorageStockParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ToolStorageStockParam param){
        ToolStorageStock oldEntity = getOldEntity(param);
        ToolStorageStock newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ToolStorageStockResult findBySpec(ToolStorageStockParam param){
        return this.baseMapper.findBySpec(param);
    }

    @Override
    public List<ToolStorageStockResult> findListBySpec(ToolStorageStockParam param){
        return this.baseMapper.findListBySpec(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(ToolStorageStockParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(ToolStorageStockParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ToolStorageStock getOldEntity(ToolStorageStockParam param) {
        return this.getById(getKey(param));
    }

    private ToolStorageStock getEntity(ToolStorageStockParam param) {
        ToolStorageStock entity = new ToolStorageStock();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	private static String getCellValue(Cell cell) {
		if (cell == null) {
			return "";
		}
		if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
				return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
			} else {
				return new BigDecimal(cell.getNumericCellValue()).toString();
			}
		} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
			return StringUtils.trimToEmpty(cell.getStringCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
			return StringUtils.trimToEmpty(cell.getCellFormula());
		} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
			return "";
		} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
			return "ERROR";
		} else {
			return cell.toString().trim();
		}
	}

    @Resource
    private BasicCustomerService basicCustomerService;

    @Resource
    private BasicPositionService basicPositionService;

    @Resource
    private UserService userService;

	@Resource
    private BasicOperateService basicOperateService;
	
	/***
	 *处理期初库存导入
	 * @param file
	 * @param ToolStorageStockParam
	 * @param data
	 * @return
	 * @throws IOException
	 */
	@Transactional(rollbackFor = Exception.class,timeout=100)
	@Override
	public ResponseData batchImport(String fileName, MultipartFile file, ToolStorageStockParam toolStorageStockParam, ResponseData data) throws IOException {
		List<ToolStorageStockParam> storageList = new ArrayList<ToolStorageStockParam>();
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
		}
		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}
		InputStream is = file.getInputStream();
		Workbook wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is);
		} else {
			wb = new XSSFWorkbook(is);
		}

		BasicCustomer basicCustomer = basicCustomerService.getById(toolStorageStockParam.getCustomerId());//客户信息
		BasicOperate basicOperate = basicOperateService.getById(toolStorageStockParam.getOperateId());//分公司信息
		BigDecimal as = new BigDecimal("0");
		User user = userService.getcurrentUser();
		Sheet sheet = wb.getSheetAt(0);
		for (int i = 1;i<sheet.getLastRowNum()+1; i++) {
			Row row = sheet.getRow(i);
			if (row == null){
				continue;
			}
			ToolStorageStockParam stockParam = new ToolStorageStockParam();
			stockParam.setCreateTime(new Date());
			
			String  goodsNumber = getCellValue(row.getCell(0));
			if (ToolUtil.isNotEmpty(goodsNumber)) {
				stockParam.setGoodsNumber(goodsNumber);//商品编号
			} else {
				break;
			}
			BasicGoodsParam basicGoodsParam = new BasicGoodsParam();
			basicGoodsParam.setGoodsNumber(goodsNumber);
			basicGoodsParam.setDeliverId(user.getDeliverId());
			basicGoodsParam.setDeptId(user.getDeptId());
			basicGoodsParam.setGoodsCustomerId(Integer.parseInt(toolStorageStockParam.getCustomerId().toString()));
			BasicGoodsResult basicGoodsResult = basicGoodsService.findBySpec(basicGoodsParam,user.getOperateId());
			if(basicGoodsResult != null) {
				basicGoodsParam.setId(basicGoodsResult.getId());	
			} 
			
			String  GoodsName = getCellValue(row.getCell(1));
			if (ToolUtil.isNotEmpty(GoodsName)) {
				stockParam.setGoodsName(GoodsName);//商品名称
			} else {
				if(basicGoodsResult == null) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					data.setSuccess(false);
					data.setMessage(goodsNumber+"商品名称不得为空");
					return data;
				} else {
					stockParam.setGoodsName(basicGoodsResult.getGoodsName());//商品名称
					stockParam.setGoodsUnit(basicGoodsResult.getGoodsUnit());
					stockParam.setGoodsSpecs(basicGoodsResult.getGoodsSpecs());
				}
			}

			String  num = getCellValue(row.getCell(5));
			if (ToolUtil.isNotEmpty(num)) {
				BigDecimal numb = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				if(numb.compareTo(as) != 1) {
					continue;
				}
				stockParam.setNum(numb.toString());//数量
			} else {
				data.setSuccess(false);
				data.setMessage("数量不得为空");
				return data;
			}

			String  positionNumber = getCellValue(row.getCell(6));
			if (ToolUtil.isNotEmpty(positionNumber)) {
				stockParam.setPositionNumber(positionNumber);//库位
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("库位编号不得为空");
				return data;
			}

			String  volume = getCellValue(row.getCell(7));
			if (ToolUtil.isNotEmpty(volume)) {
				BigDecimal volumeb = new BigDecimal(volume).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setStockVolume(volumeb.toString());//体积
			} else {
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsVolume())) {
						BigDecimal gv = new BigDecimal(basicGoodsResult.getGoodsVolume());
						BigDecimal n = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						stockParam.setStockVolume(gv.multiply(n).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
					} else {
						stockParam.setStockVolume("0.1");//体积
					}
				} else {
					stockParam.setStockVolume("0.1");//体积
				}
			}

			String  stockMoney = getCellValue(row.getCell(8));
			if (ToolUtil.isNotEmpty(stockMoney)) {
				BigDecimal stockMoneyb = new BigDecimal(stockMoney).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setStockMoney(stockMoneyb.toString());//金额
			} else {
				BigDecimal n = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsCharging())) {
						BigDecimal gp = new BigDecimal(basicGoodsResult.getGoodsCharging());
						stockParam.setStockMoney(gp.multiply(n).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					} else {
						stockParam.setStockMoney(n.toString());
					}
				} else {
					stockParam.setStockMoney(n.toString());
				}
			}

			String  stockWeight = getCellValue(row.getCell(9));
			if (ToolUtil.isNotEmpty(stockWeight)) {
				BigDecimal stockWeightb = new BigDecimal(stockWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setStockWeight(stockWeightb.toString());//重量
			} else {
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsWeight())) {
						BigDecimal gw = new BigDecimal(basicGoodsResult.getGoodsWeight());
						BigDecimal n = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						stockParam.setStockWeight(gw.multiply(n).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					} else {
						stockParam.setStockWeight("0.1");
					}
				} else {
					stockParam.setStockWeight("0.1");
				}
			}

			String  unitprice = getCellValue(row.getCell(10));
			if (ToolUtil.isNotEmpty(unitprice)) {
				BigDecimal unitpriceb = new BigDecimal(unitprice).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setUnitprice(unitpriceb.toString());//单价
			} else {
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsCharging())) {
						stockParam.setUnitprice(basicGoodsResult.getGoodsCharging());
					} else {
						stockParam.setUnitprice("10");//单价
					}
				} else {
					stockParam.setUnitprice("10");//单价
				}
			}
			
			stockParam.setDeptId(user.getDeptId());//部门id
			stockParam.setDeliverId(user.getDeliverId());//交付id
			stockParam.setStockstate("在库");
			
			stockParam.setOperateId(Long.valueOf(basicOperate.getId()));//分公司id
			stockParam.setOperateName(basicOperate.getOperateName());//分公司名称
			
			stockParam.setCustomerId(Long.valueOf(basicCustomer.getId()));//客户id
			stockParam.setCustomerName(basicCustomer.getCustomerName());//客户名称
			
			if (basicGoodsResult == null) {
				basicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
				basicGoodsParam.setGoodsName(stockParam.getGoodsName());
				basicGoodsParam.setGoodsWeight("0.1");
				if (ToolUtil.isNotEmpty(volume)) {
					BigDecimal vv = new BigDecimal(volume);
					BigDecimal n = new BigDecimal(num);
					BigDecimal GoodsVolume = vv.divide(n,4,BigDecimal.ROUND_HALF_DOWN);
					if (GoodsVolume.compareTo(as)==1) {
						basicGoodsParam.setGoodsVolume(GoodsVolume.toString());
					} else {
						basicGoodsParam.setGoodsVolume("0.1");
					}
				} else {
					basicGoodsParam.setGoodsVolume("0.1");
				}
				basicGoodsParam.setGoodsCharging("10");
				basicGoodsParam.setGoodsBottom("10");//底
				basicGoodsParam.setGoodsLamination("10");//叠层
				basicGoodsParam.setGoodsSupportvolume("1000");
				basicGoodsParam.setGoodsWarranty("36");
				basicGoodsParam.setGoodsTraylayer("1");
				basicGoodsParam.setCreateTime(new Date());
				basicGoodsService.addReturnId(basicGoodsParam);
			} 
			
			stockParam.setGoodsId(Long.valueOf(basicGoodsParam.getId()));//商品id
			
			BasicPositionParam basicPositionParam = new BasicPositionParam();
			basicPositionParam.setPositionNumber(positionNumber);
			basicPositionParam.setWarehouseId(Integer.parseInt(toolStorageStockParam.getWarehouseId().toString()));
			basicPositionParam.setDeliverId(user.getDeliverId());
			BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam,user.getDeptId(),user.getOperateId());
			if (basicPositionResult == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("库位:"+positionNumber+"不存在!");
				return data;
			}
			
			stockParam.setWarehouseId(Long.valueOf(basicPositionResult.getWarehouseId()));//仓库id
			stockParam.setWarehouseName(basicPositionResult.getWarehouseName());//仓库名称
			
			stockParam.setAreaId(Long.valueOf(basicPositionResult.getPositionAreaId()));//库区id
			stockParam.setAreaNumber(basicPositionResult.getAreaNumber());//库区编号
			
			stockParam.setPositionId(Long.valueOf(basicPositionResult.getId()));//库位id
			storageList.add(stockParam);
		}
		if (storageList.size() > 0){
			toolStorageStockService.batchAddList(storageList);
		}
		data.setSuccess(true);
		return data;
	}
    
    @Resource
    private BasicGoodsService basicGoodsService;

    @Resource
    private ToolStorageStockService toolStorageStockService;

	@Override
	public boolean batchAddList(List<ToolStorageStockParam> ssPlist) {
		return this.baseMapper.batchAddList(ssPlist);
	}

	@Override
	public void deleteBySpec(ToolStorageStockParam deleteStockParam) {
		this.baseMapper.deleteBySpec(deleteStockParam);
	}

	@Override
	public ToolStorageStockResult findTotalBySpec(ToolStorageStockParam toolStorageStockParam) {
		return this.baseMapper.findTotalBySpec(toolStorageStockParam);
	}

	@Override
	public List<ToolStorageStockResult> findGoodsListBySpec(ToolStorageStockParam toolStorageStockParam) {
		return this.baseMapper.findGoodsListBySpec(toolStorageStockParam);
	}

}
